package com.woniuxy.qiantai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.qiantai.entity.Booktype;
import com.woniuxy.qiantai.mapper.BooktypeMapper;
import com.woniuxy.qiantai.service.BooktypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author woniumrwang
 * @since 2023-02-14 10:02:36
 */
@Service
public class BooktypeServiceImpl extends ServiceImpl<BooktypeMapper, Booktype> implements BooktypeService {
    @Autowired
    BooktypeMapper booktypeMapper;
    //使用Redis默认序列化方式 实体类需要实现序列化接口
    @Autowired
    RedisTemplate redisTemplate;
    //使用自定义序列化对象
    @Autowired
    RedisTemplate<String, Object> stringObjectRedisTemplate;
    private List<Booktype> booktypeList;

    @Override
    public List<Booktype> getAll() {
    /*    if (booktypeList==null){
            booktypeList=booktypeMapper.selectList(null);
            System.out.println("如果booktypeList为空，从数据库中读取");
        }else {
            System.out.println("从缓冲中读取！");
        }
        return booktypeList;*/

        ValueOperations<String, Object> stringObjectValueOperations = stringObjectRedisTemplate.opsForValue();
        List<Booktype> booktypeList = (List<Booktype>) stringObjectValueOperations.get("booktypeList");
        System.out.println("booktypeList" + booktypeList);
        if (booktypeList == null) {
            //如果Redis数据库中没有，先从数据库中读取存到Redis中
            booktypeList = booktypeMapper.selectList(null);
            stringObjectValueOperations.set("booktypeList", booktypeList);
            System.out.println("Redis中没有，从MySQL中读取保存到Redis中");
        } else {
            System.out.println("直接从Redis中读取");
        }
        return booktypeList;
    }

    public void delete(Integer id) {
        booktypeMapper.deleteById(id);
        //清除Redis中的数据 查询的时候重新再从mysql查一遍
        stringObjectRedisTemplate.delete("booktypeList");
    }
    public void add(Booktype booktype) {
        booktypeMapper.insert(booktype);
        //清除Redis中的数据 查询的时候重新再从mysql查一遍
        stringObjectRedisTemplate.delete("booktypeList");
    }
    public void update(Booktype booktype) {
        booktypeMapper.updateById(booktype);
        //清除Redis中的数据 查询的时候重新再从mysql查一遍
        stringObjectRedisTemplate.delete("booktypeList");
    }
}
